<template>
  <div class="app-container">
    <div class="top">
      <el-input
        v-model="kwInput"
        placeholder="输入 名称 或 内容 进行筛选"
        class="input-with-select"
        clearable
        @keyup.native.enter="handleSearch"
      >
        <el-select slot="prepend" v-model="selected_website" placeholder="站点" clearable>
          <el-option
            v-for="item in websites"
            :key="item.id"
            :label="item.domain"
            :value="item.id"
          />
        </el-select>

        <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
      </el-input>
      <el-button
        type="primary"
        class="el-icon-plus add-btn"
        :disabled="listLoading"
        @click="handleAction('create', '添加长描述模版')"
      >添加长描述模版
      </el-button>
    </div>

    <el-table
      v-loading.body="listLoading"
      :data="data"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="handleSort"
    >

      <el-table-column align="center" width="100" prop="id" label="id" sortable="custom" />

      <el-table-column align="center" label="名称" width="400">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="内容">
        <template slot-scope="scope">
          <el-button size="mini" type="warning" plain @click="showText(scope.row.text)">查看</el-button>
        </template>
      </el-table-column>

      <el-table-column align="center" label="对应站点">
        <template slot-scope="scope">
          <el-tag
            v-for="item in scope.row.websites"
            :key="item.id"
            disable-transitions
          >
            {{ item.domain }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="更新时间" prop="update_at" width="155" sortable="custom">
        <template slot-scope="scope">
          <span>{{ scope.row.update_at }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="160px">
        <template slot-scope="scope">
          <el-button size="mini" type="success" plain @click="handleAction('edit', scope.row)">修改</el-button>
          <el-button size="mini" type="danger" plain @click="handleAction('delete', scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-if="data.length"
      background
      class="mt-pagination"
      :current-page="page"
      :page-sizes="[10,20,50,100]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
    />

    <el-dialog
      class="mt-dialog"
      :title="title"
      :visible.sync="dialogVisible"
      :width="width"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form v-if="action !== 'delete'" ref="dataForm" :model="temp" label-position="left" label-width="40px">
        <el-form-item label="名称">
          <el-input v-model="temp.name" />
        </el-form-item>

        <el-alert
          title="使用 {%KEY%} 该部分会被 产品属性的 KEY 字段替换,否则模版无效."
          type="warning"
          center
          show-icon
        />
        <br>
        <el-form-item label="内容">

          <tinymce ref="mt" v-model="temp.text" :height="300" />

        </el-form-item>

        <el-form-item label="对应站点" label-width="80px">
          <el-transfer
            v-model="temp.websites"
            filterable
            :filter-method="filterMethod"
            :titles="['可选站点', '已选站点']"
            filter-placeholder="输入搜索"
            :data="websites"
            :props="{
              key: 'id',
              label: 'domain'
            }"
          />
        </el-form-item>

      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/erp/elicink/longDescriptionTemplate.js'
import { Get as GetWebsite } from '@/api/erp/elicink/website'

import qs from 'qs'
import Tinymce from '@/components/Tinymce'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}

export default {
  name: 'LongDescriptionriptionTemplate',
  components: { Tinymce },
  data() {
    return {
      data: [],
      listLoading: true,
      websites: [],
      selected_website: null,
      kwInput: '',
      order_by: '',
      order_desc: '',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,

      action: null,
      dialogVisible: false,
      title: '',
      temp: {
        name: '',
        text: '',
        websites: []
      },
      width: '50%'
    }
  },
  created() {
    this.getList()
    GetWebsite().then(response => {
      this.websites = response.data.data
    })
  },
  methods: {
    resetTemp() {
      this.$nextTick(() => {
        if (this.$refs.mt.hasInit) {
          this.$refs.mt.setContent('')
        }
      })
      this.temp = {
        name: '',
        text: '',
        websites: []
      }
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc,
        website: this.selected_website
      }))
        .then(response => {
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleAction(action, row) {
      this.action = action
      this.dialogVisible = true
      switch (action) {
        case 'create':
          this.width = '50%'
          this.title = row
          this.resetTemp()

          break
        case 'delete':
          this.width = '30%'
          this.title = `确认要删除${row.name}?`
          this.temp = row
          break
        case 'edit':
          this.width = '50%'
          this.title = `修改${row.name}`
          this.temp = Object.assign({}, row)

          // this.$nextTick(() => {
          //   this.$refs.mt.setContent(row.text)
          // })
          this.$nextTick(() => {
            if (this.$refs.mt.hasInit) {
              this.$refs.mt.setContent(row.text)
            }
          })
          this.temp.websites = this.temp.websites.map(m => m.id)
          break
      }
    },
    confirm() {
      const _data = this.temp
      switch (this.action) {
        case 'create':
          Post({
            name: _data.name,
            text: _data.text,
            websites: _data.websites
          }).then(response => {
            this.dialogVisible = false
            this.getList()
            this.notify('添加成功')
          })
          return
        case 'delete':
          Delete(_data.id).then((response) => {
            this.dialogVisible = false
            this.getList()
            this.notify('删除成功')
          })
          return
        case 'edit':
          Put(_data.id, {
            name: _data.name,
            text: _data.text,
            websites: _data.websites
          }).then((response) => {
            this.dialogVisible = false
            this.getList()
            this.notify('更新成功')
          })
          return
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    showText(text) {
      this.$alert(text, '内容', {
        dangerouslyUseHTMLString: true
      })
    },
    filterMethod(query, item) {
      return item.domain.indexOf(query) > -1
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    }
  }
}
</script>

<style scoped>
  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .top >>> .el-select .el-input {
    width: 350px;
  }

  .top >>> .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }

  .top {
    padding-left: 20px;
    margin-bottom: 30px;
    margin-top: 28px;
  }

  .input-with-select {
    width: calc(100% - 200px);
  }

  .add-btn {
    float: right;
    margin-right: 20px;
    width: 150px
  }

  .mt-pagination {
    float: right;
    margin-top: 5px;
  }

  .app-container >>> .el-dialog {
    margin-top: 48px !important;
    margin-bottom: 68px;
  }

  .mt-dialog >>> .el-transfer-panel {
    width: calc(50% - 60px);
  }
</style>
